import json
from testcases.ProductGrading_Strategy.public_dispatch_way import connectMysql
from utils.logging_tool.log_control import INFO
from utils.noticeUtils.dingtalkControl import DingTalkSendMsg
from utils.times_tool.time_control import now_time_day, get_data_by_month



def test():
    """存储当天执行策略执行的数量"""
    time = now_time_day()
    cursorListingTest = connectMysql("Java_centerStrategy_Test")
    cursorListing = connectMysql("Java_centerStrategy")

    checkStrategySql = "SELECT id, bind_count, 2 AS type FROM t_strategy WHERE customer_id = 1 AND init_status = 3 AND status = 1 AND strategy_type = 2 AND is_deleted = 0"
    checkTemplateSql = "SELECT id, bind_count, 1 AS type FROM t_strategy_template  WHERE customer_id = 1 AND status = 1 AND init_status = 3 AND is_deleted = 0"
    strategyRes = cursorListing.execute_sql_many(checkStrategySql)
    templateRes = cursorListing.execute_sql_many(checkTemplateSql)
    res = strategyRes + templateRes
    sql = f"SELECT * FROM t_listing_strategy_count WHERE date = '{time}'"
    temp = cursorListingTest.execute_sql_many(sql)

    template_list = []
    strategy_list = []
    for i in res:
        type = i["type"]
        del i["type"]
        if type == 1: template_list.append(i)
        else: strategy_list.append(i)
        i = json.dumps(i)
        if not temp:
            insertSql = f"insert into t_listing_strategy_count(statistics, date, type) values('{i}','{time}', {type})"
            cursorListingTest.execute_sql_many(insertSql)

    """校验数据差异"""
    percentage = 0.1
    last_time = get_data_by_month(-1)
    last_sql = f"SELECT statistics,type FROM t_listing_strategy_count WHERE date = '{last_time}'"
    last_data = cursorListingTest.execute_sql_many(last_sql)
    last_res = []
    last_template_list = list(filter(lambda x: x["type"] == 1, last_data))
    last_strategy_list = list(filter(lambda x: x["type"] == 2, last_data))
    last_res.append(last_template_list)
    last_res.append(last_strategy_list)

    template_count = 0
    strategy_count = 0
    last_template_count = 0
    last_strategy_count = 0
    template_err = []
    strategy_err = []
    is_first = True
    for res in last_res:
        for j in res:
            statistics = json.loads(j["statistics"])
            id = statistics["id"]
            bind_count = statistics["bind_count"]
            if is_first:
                last_bind_count = list(filter(lambda x: x["id"] == id, templateRes))
                if not last_bind_count:
                    continue
                last_bind_count = last_bind_count[0]["bind_count"]
                template_count += bind_count
                last_template_count += last_bind_count
                diff = bind_count * percentage
                if abs(bind_count - last_bind_count) > diff:
                    template_err.append(str(id))
                    INFO.logger.info(f"模板ID: {id},今日匹配数据: {bind_count}, 昨日匹配数据: {last_bind_count},数据差异超过{percentage*100}%")
            else:
                last_bind_count = list(filter(lambda x: x["id"] == id, strategyRes))
                if not last_bind_count:
                    continue
                last_bind_count = last_bind_count[0]["bind_count"]
                strategy_count += bind_count
                last_strategy_count += last_bind_count
                diff = bind_count * percentage
                if abs(bind_count - last_bind_count) > diff:
                    strategy_err.append(str(id))
                    INFO.logger.info(f"策略ID: {id},今日匹配数据: {bind_count}, 昨日匹配数据: {last_bind_count},数据差异超过{percentage*100}%")
        is_first =False

    if template_err:
        template_err = template_err[:20]
        template_err = ','.join(template_err)
    else:
        template_err = "-"
    if strategy_err:
        strategy_err = strategy_err[:20]
        strategy_err = ','.join(strategy_err)
    else:
        strategy_err = "-"
    report = f"--------------------------------------------------    \n" \
                 f"**模板数据差异告警**   \n" \
                 f"今日匹配: {template_count}  \n" \
                 f"昨日匹配: {last_template_count}  \n" \
                 f"差异数量: {abs(template_count - last_template_count)}  \n" \
                 f"异常模板: {template_err}  \n" \
                 f"       \n" \
                 f"--------------------------------------------------    \n" \
                 f"**策略数据差异告警**   \n" \
                 f"今日匹配: {strategy_count}  \n" \
                 f"昨日匹配: {last_strategy_count}  \n" \
                 f"差异数量: {abs(strategy_count - last_strategy_count)}  \n" \
                 f"异常策略: {strategy_err}  \n" \
                 f"       \n" \
                 f"--------------------------------------------------    \n"


    robot_list = [
            [
                'https://oapi.dingtalk.com/robot/send?access_token=c13d51c896ff03b7d7c18414d59e7dd91bb9d67dbcb41dee36ffd9e5772b4ca4',
                'SECd5b4308d44c31e1937d6bfe20c517c4dd05887aab8cca7ad3495b53d48025846',
                [13824861341]
            ]
            # ],
            # [
            #     'https://oapi.dingtalk.com/robot/send?access_token=2ddc931959a39513c677bb5fabcee3603973a3c67f7793f1f91975e3a1bd3dcd',
            #     'SEC44371bcd1ec51cefa51a8c0fbe723beabb5c72b30ae043267b076ce414e732dc',
            #     [13824861341]
            # ]
        ]
    images = f'![screenshot](https://bpic.588ku.com/element_origin_min_pic/16/12/06/e11a89fba4c1dc29dc353697dde3b3e6.jpg)   '
    # for x in robot_list:
    #     DingTalkSendMsg().send_strategy_report(report, x[0], x[1], x[2],images)

if __name__ == '__main__':
    test()
